<?php
namespace app\api\model;

use think\Model;
use \app\manystore\model\Goods as GoodsModel;

/**
 * 購物車管理
 * Class Cart
 */
class Cart extends Model
{
    // 表名
    protected $name = 'cart';
    // 自動寫入時間戳字段
    protected $autoWriteTimestamp = 'int';

    // 定義時間戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    /* @var string $error 錯誤信息 */
    public $error = '';

    /* @var int $user_id 用戶id */
    private $user_id;

    /* @var array $cart 購物車列表 */
    private $cart = [];

    /* @var bool $clear 是否清空購物車 */
    private $clear = false;
    protected $gmodel;

    /**
     * [getCartC 獲取構造方法所需要的購物車]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T17:37:18+0800
     * @param      string                   $user_id [用戶ID]
     * @return     [type]                          [description]
     */
    public function getCartC($user_id,$where = [])
    {
        $list_buf = collection(self::field('id,spec_key,goods_id,goods_num,goods_sku_id,goods_num')->where(['user_id'=>$user_id])->where($where)->select())->toArray();
        $list = [];
        foreach ($list_buf as $key => $value) {
            $list[$value['spec_key']] = $value;
        }
        return $list;
    }

    /**
     * 購物車列表
     */
    public function getList($user_id,$cart_id = [])
    {
        $where = [];
        if ( $cart_id ) {
            $where = ['id'=>['in',$cart_id]];
        }
        $cart_list = $this->getCartC($user_id,$where);
        // 商品列表
        $goodsList = [];
        $goodsIds = array_unique(array_column($cart_list, 'goods_id'));
        foreach ((new GoodsModel)->getListByIdsCart($goodsIds) as $goods) {
            $goodsList[$goods['goods_id']] = $goods;
        }
        // 訂單總運費金額
        $expressPrice = 0.00;
        // 購物車商品列表
        $cartList = [];
        // 區分商家訂單列表
        $shopList = [];
        foreach ($cart_list as $key => $cart) {
            // 判斷商品不存在則自動刪除
            if (!isset($goodsList[$cart['goods_id']])) {
                $spec_key = $cart['goods_id'] . '_' . $cart['goods_sku_id'];
                self::delCartGoodsSpec($spec_key);
                continue;
            }
            /* @var Goods $goods */
            $goods = $goodsList[$cart['goods_id']];
            // 商品sku信息
            $goods['goods_sku_id'] = $cart['goods_sku_id'];
            // 商品sku不存在則自動刪除
            if (!$goods['goods_sku'] = $goods->getGoodsSku($cart['goods_sku_id'])) {
                $spec_key = $cart['goods_id'] . '_' . $cart['goods_sku_id'];
                self::delCartGoodsSpec($spec_key);
                continue;
            }
            $goods['show_error'] = 0;
            $goods['show_error_text'] = '';
            $expressPrice += $goods['delivery_price'];
            // 判斷商品是否下架
            if ($goods['goods_status']!== '10') {
                $spec_key = $cart['goods_id'] . '_' . $cart['goods_sku_id'];
                self::delCartGoodsSpec($spec_key);
                continue;
            }
            // 判斷商品是否普通商品
            if ($goods['type']!== '1') {
                $spec_key = $cart['goods_id'] . '_' . $cart['goods_sku_id'];
                self::delCartGoodsSpec($spec_key);
                continue;
            }
            // 判斷商品庫存
            if ($cart['goods_num'] > $goods['goods_sku']['stock_num']) {
                $goods['show_error'] = 2;
                $goods['show_error_text'] = '庫存不足';
                $this->setError('很抱歉，商品 [' . $goods['goods_name'] . $goods['goods_sku']['goods_attr'] . '] 庫存不足');
            }
            // 商品單價
            $goods['goods_price'] = $goods['goods_sku']['goods_price'];
            // 商品積分
            $goods['integral'] = $goods['goods_sku']['integral'];
            // 商品總價
            $goods['total_num'] = $cart['goods_num'];
            $goods['total_price'] = $total_price = bcmul($goods['goods_price'], $cart['goods_num'], 2);
            $goods['total_integral'] = $integral = bcmul($goods['integral'], $cart['goods_num'], 2);

            $shop_id = $goods['shop_id'];

            $goods = $goods->toArray();
            // 刪除一些不要的參數
            unset($goods['cat_id']);
            unset($goods['shop_cat_id']);
            unset($goods['deduct_stock_type']);
            unset($goods['deletetime']);
            unset($goods['spec']);
            unset($goods['specRel']);
            unset($goods['createtime']);
            unset($goods['updatetime']);
            // unset($goods['shop_id']);
            // unset($goods['content']);
            unset($goods['sales_initial']);
            unset($goods['sales_actual']);
            unset($goods['weigh']);
            unset($goods['type']);
            $goods['cart_id'] = $cart['id'];
            $shopList[$shop_id][] = $cartList[] = $goods;
        }
        $shopListBuf = [];
        foreach ($shopList as $key => $value) {
            $shop = db('manystore_shop')->where(['id'=>$key])->find();
            // 商品總金額
            $shopTotalPrice = array_sum(array_column($value, 'total_price'));
            // 總積分
            $shopTotalIntegral = array_sum(array_column($value, 'total_integral'));
            // 總運費
            $shopTotalDeliveryPrice = array_sum(array_column($value, 'delivery_price'));
            // 實際支付金額(已包含運費)
            $orderPayPrice = bcadd($shopTotalPrice, $shopTotalDeliveryPrice, 2);

            $array = ['shop_id'=>$shop['id'],'logo'=>$shop['logo'],'name'=>$shop['name'],'shopTotalPrice'=>$shopTotalPrice,'shopTotalIntegral'=>$shopTotalIntegral,'shopTotalDeliveryPrice'=>$shopTotalDeliveryPrice,'orderPayPrice'=>$orderPayPrice,'goods_list'=>$value];
            $shopListBuf[] = $array;
        }
        // 商品總金額
        $orderTotalPrice = array_sum(array_column($cartList, 'total_price'));
        // 總積分
        $orderTotalIntegral = array_sum(array_column($cartList, 'total_integral'));
        // 所有商品的運費金額
        return [
            'goods_list' => $shopListBuf,                       // 商品列表
            'order_total_num' => $this->getTotalNum($user_id,$where),       // 商品總數量
            'order_total_price' => round($orderTotalPrice, 2),              // 商品總金額 (不含運費)
            'delivery_price' => round($expressPrice, 2),              // 運費
            'order_pay_price' => bcadd($orderTotalPrice, $expressPrice, 2),    // 實際支付金額(已包含運費)
            'orderTotalIntegral' => round($orderTotalIntegral, 2),    // 總積分
            'has_error' => $this->hasError(),
            'error_msg' => $this->getError(),
        ];
    }

    /**
     * [delCartGoodsSpec 根據skukey刪除購物車]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T19:46:10+0800
     * @param      [type]                   $spec_key [description]
     * @return     [type]                             [description]
     */
    public function delCartGoodsSpec($spec_key)
    {
        self::where(['spec_key'=>$spec_key])->delete();
    }


    /**
     * [addCart 增加購物車]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T19:44:33+0800
     * @param      [type]                   $user_id      [用戶ID]
     * @param      [type]                   $goods_id     [商品ID]
     * @param      [type]                   $goods_num    [增加數量]
     * @param      [type]                   $goods_sku_id [商品sku]
     */
    public function addCart($user_id,$goods_id,$goods_num,$goods_sku_id)
    {
        $gmodel = new GoodsModel;
        $cart_list = $this->getCartC($user_id);
        // 購物車商品索引
        $index = $goods_id . '_' . $goods_sku_id;
        // 商品信息
        $goods = $gmodel->detail($goods_id);
        if ( $goods['type'] == '2' ) {
            $this->setError('積分商品不能加入購物車');
            return false;
        }
        // 商品sku信息
        $goods['goods_sku'] = $goods->getGoodsSku($goods_sku_id);
        // 判斷商品是否下架
        if ($goods['goods_status'] !== '10') {
            $this->setError('很抱歉，該商品已下架');
            return false;
        }
        // 判斷商品庫存
        $cartGoodsNum = $goods_num + (isset($cart_list[$index]) ? $cart_list[$index]['goods_num'] : 0);
        if ($cartGoodsNum > $goods['goods_sku']['stock_num']) {
            $this->setError('很抱歉，商品庫存不足');
            return false;
        }

        $time = time();

        $cart = self::getCart($user_id);
        // 如果購物車不存在或者商品不存在購物車
        $cart_goods = self::getCartGoods($index,$user_id);
        if ( !$cart || !$cart_goods ) {
            // 商品信息
            $goods = $gmodel->detail($goods_id);
            $insert = [];
            $insert['user_id'] = $user_id;
            $insert['spec_key'] = $index;
            $insert['goods_id'] = $goods_id;
            $insert['goods_num'] = $goods_num;
            $insert['goods_sku_id'] = $goods_sku_id?$goods_sku_id:'';
            $insert['create_time'] = $time;
            $insert['shop_id'] = $goods['shop_id'];
            $status = self::insert($insert);
        }else{
            $status = self::where(['id'=>$cart_goods['id']])->setInc('goods_num',$goods_num);
        }

        if ( !$status ) {
            $this->setError('操作失敗');
            return false;
        }

        return true;
    }

    /**
     * [getCart 獲取購物車]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T18:19:36+0800
     * @param      integer                  $user_id [用戶ID]
     * @param      string                   $field   [查找條件]
     * @return     [type]                            [description]
     */
    public function getCart($user_id=0,$field='spec_key,goods_num,goods_id,goods_sku_id,user_id')
    {
        $where_cart = [];
        $where_cart['user_id'] = $user_id;

        // 查詢數據庫
        $cart = self::field($field)
                ->where($where_cart)
                ->select();

        $cat_buf = [];
        foreach ($cart as $key => $value) {
            if ( !isset($cat_buf[$value['spec_key']]) ) {

                $cat_buf[$value['spec_key']]['spec_key'] = $value['spec_key'];
                $cat_buf[$value['spec_key']]['goods_num'] = $value['goods_num'];
                $cat_buf[$value['spec_key']]['goods_id'] = $value['goods_id'];
                $cat_buf[$value['spec_key']]['goods_sku_id'] = $value['goods_sku_id'];
                $cat_buf[$value['spec_key']]['user_id'] = $value['user_id'];

            }else{
                $cat_buf[$value['spec_key']]['goods_num'] += $value['goods_num'];
            }
        }
        return $cat_buf;
    }

    /**
     * [getCartGoods 獲取購物車商品]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T18:23:55+0800
     * @param      [type]                   $spec_key [商品SKUKEY]
     * @param      [type]                   $user_id  [用戶ID]
     * @return     [type]                             [description]
     */
    public function getCartGoods($spec_key,$user_id)
    {
        $where_cart = [];
        $where_cart['spec_key'] = $spec_key;
        $where_cart['user_id'] = $user_id;
        $cart_goods = self::where($where_cart)->find();
        return $cart_goods;
    }

    /**
     * [subCart 刪減購物車]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T18:44:26+0800
     * @param      [type]                   $user_id      [用戶ID]
     * @param      [type]                   $goods_id     [商品id]
     * @param      [type]                   $goods_sku_id [商品SKU]
     * @param      [type]                   $goods_num    [商品數量]
     * @return     [type]                                 [description]
     */
    public function subCart($user_id,$goods_id,$goods_sku_id,$goods_num)
    {
        $spec_key = $goods_id . '_' . $goods_sku_id;

        $cart_goods = self::getCartGoods($spec_key,$user_id);

        // 如果購物車不存在或者商品不存在購物車
        $status = 1;
        if ( $cart_goods ) {
            if ( $cart_goods['goods_num'] > $goods_num ) {
                $status = self::where(['id'=>$cart_goods['id']])->setDec('goods_num',$goods_num);

            }else{
                $where_cart = [];
                $where_cart['spec_key'] = $spec_key;
                $where_cart['user_id'] = $user_id;
                $status = self::where($where_cart)->delete();
            }
        }
        if ( !$status ) {
            $this->setError('操作失敗');
            return false;
        }

        return true;
    }

    /**
     * 刪除購物車中指定商品
     * @param $goods_id
     * @param $goods_sku_id
     */
    public function deleteCart($goods_id, $goods_sku_id)
    {
        $index = $goods_id . '_' . $goods_sku_id;
        unset($this->cart[$index]);
    }

    /**
     * 獲取當前用戶購物車商品總數量
     * @return int
     */
    public function getTotalNum($user_id,$where = [])
    {
        $where_cart['user_id'] = $user_id;
        $total_num = self::where($where_cart)->where($where)->sum('goods_num');
        return $total_num;
    }

    /**
     * [clearAll description]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T20:18:29+0800
     * @param      integer                  $user_id [description]
     * @return     [type]                            [description]
     */
    public function clearAll($user_id=0,$where=[])
    {
        $where_cart = [];
        $where_cart['user_id'] = $user_id;
        db('cart')
        ->where($where_cart)
        ->where($where)
        ->delete();
    }

    /**
     * 設置錯誤信息
     * @param $error
     */
    private function setError($error)
    {
        empty($this->error) && $this->error = $error;
    }

    /**
     * 是否存在錯誤
     * @return bool
     */
    private function hasError()
    {
        return !empty($this->error);
    }

    /**
     * 獲取錯誤信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

}
